#include "ReminderWidget.h"
#include "StyleLoader.h"
#include <QTableWidget>
#include <QVBoxLayout>
#include "FileLineEdit.h"
#include "ConfigService.h"
#include "SoundService.h"
#include <QSlider>
#include <QSpinBox>

ReminderWidget::ReminderWidget(QWidget *parent)
    : QWidget{parent}
{
    initData();
    
    // 从QSS文件加载样式
    QString style = StyleLoader::loadDarkTheme();
    if (!style.isEmpty()) {
        setStyleSheet(style);
    } else {
        qWarning() << "警告：样式文件加载失败！请检查 resource.qrc 配置。";
    }
    
    setupForm();
}

void ReminderWidget::setupForm()
{
    // 创建主布局
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->setSpacing(15);
    mainLayout->setContentsMargins(20, 20, 20, 20);

    QGroupBox *headGroup = new QGroupBox("声音提醒设置", this); // 设置父对象为 this
    QGridLayout * headLayout = new QGridLayout (headGroup); // 设置父对象为 headGroup
    headLayout->setSpacing(12);
    headLayout->setContentsMargins(15, 20, 15, 15);
    startSoundFileEdit = new FileLineEdit(headGroup);
    startSoundFileEdit->setFixedWidth(250);
    startSoundFileEdit->setFileLineEditType(FileLineEdit::FileLineEditType::Music);
    warn1SoundFileEdit = new FileLineEdit(headGroup);
    warn1SoundFileEdit->setFixedWidth(250);
    warn1SoundFileEdit->setFileLineEditType(FileLineEdit::FileLineEditType::Music);
    warn2SoundFileEdit = new FileLineEdit(headGroup);
    warn2SoundFileEdit->setFixedWidth(250);
    warn2SoundFileEdit->setFileLineEditType(FileLineEdit::FileLineEditType::Music);
    warn3SoundFileEdit = new FileLineEdit(headGroup);
    warn3SoundFileEdit->setFixedWidth(250);
    warn3SoundFileEdit->setFileLineEditType(FileLineEdit::FileLineEditType::Music);
    timeoutSoundFileEdit = new FileLineEdit(headGroup);
    timeoutSoundFileEdit->setFixedWidth(250);
    timeoutSoundFileEdit->setFileLineEditType(FileLineEdit::FileLineEditType::Music);
    endSoundFileEdit = new FileLineEdit(headGroup);
    endSoundFileEdit->setFixedWidth(250);
    endSoundFileEdit->setFileLineEditType(FileLineEdit::FileLineEditType::Music);

    startSoundCombo = new QCheckBox(headGroup);
    warn1SoundCombo = new QCheckBox(headGroup);
    warn1FlashCombo = new QCheckBox(headGroup);
    warn1TextCombo = new QCheckBox(headGroup);
    warn2SoundCombo = new QCheckBox(headGroup);
    warn2FlashCombo = new QCheckBox(headGroup);
    warn2TextCombo = new QCheckBox(headGroup);
    warn3SoundCombo = new QCheckBox(headGroup);
    warn3FlashCombo = new QCheckBox(headGroup);
    warn3TextCombo = new QCheckBox(headGroup);
    timeoutSoundCombo = new QCheckBox(headGroup);
    timeoutFlashCombo = new QCheckBox(headGroup);
    timeoutTextCombo = new QCheckBox(headGroup);
    endSoundCombo = new QCheckBox(headGroup);
    endTextCombo = new QCheckBox(headGroup);


    // 添加标题行
    QLabel *voiceLabel = new QLabel("启用声音");
    voiceLabel->setStyleSheet("font-weight: bold; color: #4CAF50;");
    QLabel *flashLabel = new QLabel("闪烁效果");
    flashLabel->setStyleSheet("font-weight: bold; color: #4CAF50;");
    QLabel *textLabel = new QLabel("显示文字");
    textLabel->setStyleSheet("font-weight: bold; color: #4CAF50;");

    headLayout->addWidget(voiceLabel,0,2, Qt::AlignCenter);
    headLayout->addWidget(flashLabel,0,3, Qt::AlignCenter);
    headLayout->addWidget(textLabel,0,4, Qt::AlignCenter);

    headLayout->addWidget(new QLabel("开始"),1,0);
    headLayout->addWidget(startSoundFileEdit,1,1);
    headLayout->addWidget(startSoundCombo,1,2);
    headLayout->addWidget(new QLabel("报警1"),2,0);
    headLayout->addWidget(warn1SoundFileEdit,2,1);
    headLayout->addWidget(warn1SoundCombo,2,2);
    headLayout->addWidget(warn1FlashCombo,2,3);
    headLayout->addWidget(warn1TextCombo,2,4);
    headLayout->addWidget(new QLabel("报警2"),3,0);
    headLayout->addWidget(warn2SoundFileEdit,3,1);
    headLayout->addWidget(warn2SoundCombo,3,2);
    headLayout->addWidget(warn2FlashCombo,3,3);
    headLayout->addWidget(warn2TextCombo,3,4);
    headLayout->addWidget(new QLabel("报警3"),4,0);
    headLayout->addWidget(warn3SoundFileEdit,4,1);
    headLayout->addWidget(warn3SoundCombo,4,2);
    headLayout->addWidget(warn3FlashCombo,4,3);
    headLayout->addWidget(warn3TextCombo,4,4);
    headLayout->addWidget(new QLabel("超时"),5,0);
    headLayout->addWidget(timeoutSoundFileEdit,5,1);
    headLayout->addWidget(timeoutSoundCombo,5,2);
    headLayout->addWidget(timeoutFlashCombo,5,3);
    headLayout->addWidget(timeoutTextCombo,5,4);
    headLayout->addWidget(new QLabel("结束"),6,0);
    headLayout->addWidget(endSoundFileEdit,6,1);
    headLayout->addWidget(endSoundCombo,6,2);
    headLayout->addWidget(endTextCombo,6,4);

    // headLayout在第32行创建时已经指定了headGroup为父对象，不需要再次setLayout
    mainLayout->addWidget(headGroup);

    setSoundData();

    QGroupBox *otherGroup = new QGroupBox("其他设置",this); // 设置父对象为 this
    QVBoxLayout * otherLayout = new QVBoxLayout (otherGroup); // 设置父对象为 otherGroup
    otherLayout->setSpacing(15);
    otherLayout->setContentsMargins(15, 20, 15, 15);
    QHBoxLayout *head1 = new QHBoxLayout();  // 不指定父对象
    QLabel *timeoutLabel = new QLabel("超时时钟");
    timeoutCombo = new QComboBox(otherGroup);
    timeoutCombo->addItems({"无变化", "选项1", "选项2"}); // 示例选项
    head1->addWidget(timeoutLabel);
    head1->addWidget(timeoutCombo);
    head1->addStretch();
    otherLayout->addLayout(head1);
    otherLayout->addSpacing(20);
    QHBoxLayout *head2 = new QHBoxLayout();  // 不指定父对象
    orderCheck = new QCheckBox("按时钟名称顺序循环计时",otherGroup);
    screenSaverCheck = new QCheckBox("屏幕保护色",otherGroup);
    head2->addWidget(orderCheck);
    head2->addWidget(screenSaverCheck);
    head2->addStretch();
    otherLayout->addLayout(head2);
    otherLayout->addSpacing(20);
    QHBoxLayout *head3 = new QHBoxLayout();  // 不指定父对象
    hotkeyCheck = new QCheckBox("开始/停止热键相同",otherGroup);
    head3->addWidget(hotkeyCheck);
    head3->addStretch();
    otherLayout->addLayout(head3);
    otherLayout->addSpacing(20);
    // otherLayout在第117行创建时已经指定了otherGroup为父对象，不需要再次setLayout
    mainLayout->addWidget(otherGroup);

    // 全局声音设置
    QGroupBox *globalSound = new QGroupBox("全局声音", this);
    QGridLayout *gl = new QGridLayout(globalSound);
    chkMuted = new QCheckBox("静音", globalSound);
    gl->addWidget(chkMuted, 0, 0);
    gl->addWidget(new QLabel("音量:", globalSound), 0, 1);
    sliderVolume = new QSlider(Qt::Horizontal, globalSound);
    sliderVolume->setRange(0, 100);
    gl->addWidget(sliderVolume, 0, 2);
    lblVolumeValue = new QLabel("100", globalSound);
    gl->addWidget(lblVolumeValue, 0, 3);

    chkTickEnable = new QCheckBox("启用嘀嗒声", globalSound);
    gl->addWidget(chkTickEnable, 1, 0);
    gl->addWidget(new QLabel("嘀嗒间隔(ms):", globalSound), 1, 1);
    spinTickInterval = new QSpinBox(globalSound);
    spinTickInterval->setRange(100, 5000);
    spinTickInterval->setSingleStep(100);
    spinTickInterval->setValue(1000);
    gl->addWidget(spinTickInterval, 1, 2);

    // 预览按钮
    btnPreviewStart = new QPushButton("预览-开始", globalSound);
    btnPreviewAlarm1 = new QPushButton("预览-闹钟1", globalSound);
    btnPreviewAlarm2 = new QPushButton("预览-闹钟2", globalSound);
    btnPreviewAlarm3 = new QPushButton("预览-闹钟3", globalSound);
    btnPreviewTimeout = new QPushButton("预览-超时", globalSound);
    btnPreviewEnd = new QPushButton("预览-结束", globalSound);
    gl->addWidget(btnPreviewStart, 2, 0);
    gl->addWidget(btnPreviewAlarm1, 2, 1);
    gl->addWidget(btnPreviewAlarm2, 2, 2);
    gl->addWidget(btnPreviewAlarm3, 3, 0);
    gl->addWidget(btnPreviewTimeout, 3, 1);
    gl->addWidget(btnPreviewEnd, 3, 2);
    gl->setColumnStretch(2, 1);
    mainLayout->addWidget(globalSound);
    // 按钮布局
    mainLayout->addStretch(); // 添加弹性空间，将按钮推到底部
    
    QHBoxLayout *buttonLayout = new QHBoxLayout();
    buttonLayout->setSpacing(10);
    buttonLayout->addStretch(); // 将按钮推到右侧
    
    btnSpecialCount = new QPushButton("特定计时", this);
    btnSpecialCount->setProperty("styleClass", "secondary");
    
    btnHelp = new QPushButton("帮助", this);
    btnHelp->setProperty("styleClass", "secondary");
    
    btnApply = new QPushButton("应用", this);
    btnApply->setProperty("styleClass", "primary");
    connect(btnApply,&QPushButton::clicked,this,&ReminderWidget::onSaveDataBtn);
    
    btnClose = new QPushButton("关闭", this);
    btnClose->setProperty("styleClass", "secondary");
    connect(btnClose,&QPushButton::clicked,this,[this](){emit sigClose();});
    
    buttonLayout->addWidget(btnSpecialCount);
    buttonLayout->addWidget(btnHelp);
    buttonLayout->addWidget(btnApply);
    buttonLayout->addWidget(btnClose);
    
    mainLayout->addLayout(buttonLayout);

    setLayout(mainLayout);

    connectGlobalSoundControls();
}

void ReminderWidget::initData()
{
    // ✅ 使用ConfigService获取音频配置
    m_soundSettings = ConfigService::instance().getSoundSettings();
}

void ReminderWidget::saveData()
{
    // ✅ 使用ConfigService保存音频配置
    ConfigService::instance().setSoundSettings(m_soundSettings);
    ConfigService::instance().saveConfig();
}

void ReminderWidget::setSoundData()
{
    startSoundFileEdit->setText(m_soundSettings.start.soundFilePath);
    startSoundCombo->setChecked(m_soundSettings.start.isSoundEnabled);


    warn1SoundFileEdit->setText(m_soundSettings.alarm1.soundFilePath);
    warn1SoundCombo->setChecked(m_soundSettings.alarm1.isSoundEnabled);
    warn1FlashCombo->setChecked(m_soundSettings.alarm1.isFlashing);
    warn1TextCombo->setChecked(m_soundSettings.alarm1.isTextVisible);

    warn2SoundFileEdit->setText(m_soundSettings.alarm2.soundFilePath);
    warn2SoundCombo->setChecked(m_soundSettings.alarm2.isSoundEnabled);
    warn2FlashCombo->setChecked(m_soundSettings.alarm2.isFlashing);
    warn2TextCombo->setChecked(m_soundSettings.alarm2.isTextVisible);

    warn3SoundFileEdit->setText(m_soundSettings.alarm3.soundFilePath);
    warn3SoundCombo->setChecked(m_soundSettings.alarm3.isSoundEnabled);
    warn3FlashCombo->setChecked(m_soundSettings.alarm3.isFlashing);
    warn3TextCombo->setChecked(m_soundSettings.alarm3.isTextVisible);


    timeoutSoundFileEdit->setText(m_soundSettings.timeout.soundFilePath);
    timeoutSoundCombo->setChecked(m_soundSettings.timeout.isSoundEnabled);
    timeoutFlashCombo->setChecked(m_soundSettings.timeout.isFlashing);
    timeoutTextCombo->setChecked(m_soundSettings.timeout.isTextVisible);

    endSoundFileEdit->setText(m_soundSettings.end.soundFilePath);
    endSoundCombo->setChecked(m_soundSettings.end.isSoundEnabled);
    endTextCombo->setChecked(m_soundSettings.end.isTextVisible);
}

void ReminderWidget::getSoundData()
{
    m_soundSettings.start.soundFilePath = startSoundFileEdit->text();
    m_soundSettings.start.isSoundEnabled = startSoundCombo->isChecked();


    m_soundSettings.alarm1.soundFilePath = warn1SoundFileEdit->text();
    m_soundSettings.alarm1.isSoundEnabled = warn1SoundCombo->isChecked();
    m_soundSettings.alarm1.isFlashing = warn1FlashCombo->isChecked();
    m_soundSettings.alarm1.isTextVisible = warn1TextCombo->isChecked();

    m_soundSettings.alarm2.soundFilePath = warn2SoundFileEdit->text();
    m_soundSettings.alarm2.isSoundEnabled = warn2SoundCombo->isChecked();
    m_soundSettings.alarm2.isFlashing = warn2FlashCombo->isChecked();
    m_soundSettings.alarm2.isTextVisible = warn2TextCombo->isChecked();

    m_soundSettings.alarm3.soundFilePath = warn3SoundFileEdit->text();
    m_soundSettings.alarm3.isSoundEnabled = warn3SoundCombo->isChecked();
    m_soundSettings.alarm3.isFlashing = warn3FlashCombo->isChecked();
    m_soundSettings.alarm3.isTextVisible = warn3TextCombo->isChecked();

    m_soundSettings.timeout.soundFilePath = timeoutSoundFileEdit->text();
    m_soundSettings.timeout.isSoundEnabled = timeoutSoundCombo->isChecked();
    m_soundSettings.timeout.isFlashing = timeoutFlashCombo->isChecked();
    m_soundSettings.timeout.isTextVisible = timeoutTextCombo->isChecked();

    m_soundSettings.end.soundFilePath = endSoundFileEdit->text();
    m_soundSettings.end.isSoundEnabled = endSoundCombo->isChecked();
    m_soundSettings.end.isTextVisible = endTextCombo->isChecked();
}

void ReminderWidget::onSaveDataBtn()
{
    getSoundData();

    saveData();
    // ✅ ConfigService::saveConfig() 已经会发出信号，无需再次调用UpdatData

    update();
}

void ReminderWidget::connectGlobalSoundControls()
{
    // 初始化全局状态（先读配置，再同步服务）
    chkMuted->setChecked(ConfigService::instance().getGlobalMuted());
    sliderVolume->setValue(ConfigService::instance().getGlobalVolume());
    lblVolumeValue->setText(QString::number(sliderVolume->value()));
    if (ConfigService::instance().getTickEnable()) {
        SoundService::instance().setTickInterval(ConfigService::instance().getTickIntervalMs());
        SoundService::instance().startTickSound(qMax(10, sliderVolume->value()/3));
        chkTickEnable->setChecked(true);
        spinTickInterval->setValue(ConfigService::instance().getTickIntervalMs());
    } else {
        chkTickEnable->setChecked(false);
    }
    // 同步到运行服务
    SoundService::instance().setMuted(chkMuted->isChecked());
    SoundService::instance().setVolume(sliderVolume->value());

    connect(chkMuted, &QCheckBox::stateChanged, this, &ReminderWidget::onMuteChanged);
    connect(sliderVolume, &QSlider::valueChanged, this, &ReminderWidget::onVolumeChanged);
    connect(chkTickEnable, &QCheckBox::stateChanged, this, &ReminderWidget::onTickEnableChanged);
    connect(spinTickInterval, QOverload<int>::of(&QSpinBox::valueChanged), this, &ReminderWidget::onTickIntervalChanged);
    connect(btnPreviewStart, &QPushButton::clicked, this, &ReminderWidget::onPreviewStart);
    connect(btnPreviewAlarm1, &QPushButton::clicked, this, &ReminderWidget::onPreviewAlarm1);
    connect(btnPreviewAlarm2, &QPushButton::clicked, this, &ReminderWidget::onPreviewAlarm2);
    connect(btnPreviewAlarm3, &QPushButton::clicked, this, &ReminderWidget::onPreviewAlarm3);
    connect(btnPreviewTimeout, &QPushButton::clicked, this, &ReminderWidget::onPreviewTimeout);
    connect(btnPreviewEnd, &QPushButton::clicked, this, &ReminderWidget::onPreviewEnd);
}

void ReminderWidget::onMuteChanged(int state)
{
    bool m = (state == Qt::Checked);
    SoundService::instance().setMuted(m);
    ConfigService::instance().setGlobalMuted(m);
}

void ReminderWidget::onVolumeChanged(int value)
{
    lblVolumeValue->setText(QString::number(value));
    SoundService::instance().setVolume(value);
    ConfigService::instance().setGlobalVolume(value);
}

void ReminderWidget::onTickEnableChanged(int state)
{
    bool en = (state == Qt::Checked);
    ConfigService::instance().setTickEnable(en);
    if (en) {
        SoundService::instance().setTickInterval(spinTickInterval->value());
        SoundService::instance().startTickSound(qMax(10, SoundService::instance().getVolume()/3));
    } else {
        SoundService::instance().stopTickSound();
    }
}

void ReminderWidget::onTickIntervalChanged(int value)
{
    SoundService::instance().setTickInterval(value);
    ConfigService::instance().setTickIntervalMs(value);
}

void ReminderWidget::onPreviewStart(){ SoundService::instance().playAlarm(TipType::START,   m_soundSettings); }
void ReminderWidget::onPreviewAlarm1(){ SoundService::instance().playAlarm(TipType::ALARM1, m_soundSettings); }
void ReminderWidget::onPreviewAlarm2(){ SoundService::instance().playAlarm(TipType::ALARM2, m_soundSettings); }
void ReminderWidget::onPreviewAlarm3(){ SoundService::instance().playAlarm(TipType::ALARM3, m_soundSettings); }
void ReminderWidget::onPreviewTimeout(){ SoundService::instance().playAlarm(TipType::TIMEOUT, m_soundSettings); }
void ReminderWidget::onPreviewEnd(){ SoundService::instance().playAlarm(TipType::END,     m_soundSettings); }
